package com.electronic.domain;


import com.electronic.enums.AlgorithmEnum;
import lombok.Data;
import lombok.Getter;
import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;

import java.security.*;
import java.security.cert.Certificate;

/**
 * SignConfiguration 类用于存储和管理签名相关的配置信息。
 */
@Data
public class SignatureConfig {
    /**
     * SM2 私钥
     */
    @Getter
    public static PrivateKey sm2PrivateKey;
    /**
     * RSA 私钥
     */
    @Getter
    public static PrivateKey rsaPrivateKey;
    /**
     * 签名算法
     */
    private AlgorithmEnum algorithmType;
    /**
     * 签名证书
     */
    private Certificate sigCert = null;
    /**
     * 证书链
     */
    private Certificate[] certChain = null;
    /**
     * PDF GMT 签名器
     */
    private PdfGmtSigner gmtSigner = null;
    /**
     * PKCS7 签名的估计大小
     */
    private int pkcs7EstimatedSize = 8192;

    static {

        try {
            // 注册 Bouncy Castle 提供者
            Security.addProvider(new BouncyCastleProvider());
            // 获取 SM2 参数规范
            ECParameterSpec sm2Spec = ECNamedCurveTable.getParameterSpec(GMObjectIdentifiers.sm2p256v1.getId());
            // 创建密钥对生成器并初始化
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("EC", "BC");
            keyPairGen.initialize(sm2Spec);
            // 生成密钥对
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // 获取私钥
            sm2PrivateKey = keyPair.getPrivate();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            KeyPairGenerator rsaKeyPairGen=KeyPairGenerator.getInstance("RSA");
            rsaKeyPairGen.initialize(2048, new SecureRandom());
            KeyPair keyPair = rsaKeyPairGen.generateKeyPair();
            rsaPrivateKey = keyPair.getPrivate();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置证书链
     *
     * @param chain 证书链数组
     */
    public void setChain(Certificate[] chain) {
        this.certChain = chain;
        this.sigCert = this.certChain[0];
    }
}
